package com.isman.placeslist;

import java.lang.reflect.Type;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.isman.placeslist.adapter.StatusAdapter;
import com.isman.placeslist.adapter.StatusAdapterEvent;
import com.isman.placeslist.apiobject.Status;
import com.isman.placeslist.ws.AsyncRunnerHeadler;
import com.isman.placeslist.ws.ServiceProvider;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
import android.widget.ProgressBar;

public class TabUserBoard extends Activity {
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tab_user_board);
		mUserId = getIntent().getExtras().getLong(PageUser.USER_ID);

		init();
		initData();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case PageStatus.STATUS_DETAIL:
			int index = data.getExtras().getInt(PageStatus.STATUS_INDEX, 0);
			Status status = (Status) data.getExtras().getSerializable(
					PageStatus.STATUS_INFO);
			mStatusList.set(index, status);
			mStatusAdapter.notifyDataSetChanged();
			break;
		}
	}

	protected void init() {
		vLvList = (ListView) findViewById(R.id.lvw_userBoard_list);
		vProgressBar = (ProgressBar) findViewById(R.id.pgb_head_load);
	}

	protected void initData() {
		StatusAdapterEvent event = new StatusAdapterEvent(this, mStatusList,
				vProgressBar);
		mStatusAdapter = new StatusAdapter(this, event, mStatusList);
		event.setAdapter(mStatusAdapter);
		vLvList.setAdapter(mStatusAdapter);

		ServiceProvider provider = new ServiceProvider(this);
		provider.LoadFeed(mUserId, new AsyncRunnerHeadler() {
			@Override
			public void onComplete(String json) {
				Log.d("TAG", json);
				Type type = new TypeToken<ArrayList<Status>>() {
				}.getType();

				final ArrayList<Status> status = new Gson()
						.fromJson(json, type);
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mStatusList.clear();
						mStatusList.addAll(status);
						mStatusAdapter.notifyDataSetChanged();
					}
				});
			}

			@Override
			public void onAuthenticate(String json) {
			}

			@Override
			public void onError(int statusCode, String json) {
			}

			@Override
			public void onConnectingError(String message) {
			}
		});
	}

	private long mUserId;
	private StatusAdapter mStatusAdapter;
	private ArrayList<Status> mStatusList = new ArrayList<Status>();

	private ProgressBar vProgressBar;
	private ListView vLvList;
}
